<template>
  <div class="main">
    <div class="title">
      <div>区域管理</div>
      <el-button type="primary" :icon="CirclePlus" @click="addArea"
        >新增区域</el-button
      >
    </div>
    <div class="search-bar">
      <div class="label-input">
        <span>搜索内容：</span>
        <el-input v-model="query.queryName" style="width: 200px" />
      </div>
      <el-button class="search-btn" @click="getTabelData">查询</el-button>
      <el-button type="info" @click="reset">重置</el-button>
    </div>
    <div class="cut-line"></div>
    <el-table
      :data="tabelData"
      height="400"
      style="width: 100%"
      border
      v-loading="loading"
      :header-cell-style="headerStyle"
      :row-class-name="tableRowClassName"
    >
      <el-table-column type="index" align="center" label="#" width="50" />
      <el-table-column
        prop="name"
        align="center"
        label="区域名称"
        width="200"
      />
      <el-table-column
        prop="address"
        align="center"
        label="区域地址"
        width="500"
      />
      <el-table-column
        prop="isDeleted"
        align="center"
        label="状态"
        width="100"
      />
      <el-table-column align="center" label="操作">
        <template v-slot="scope">
          <div class="table-buts">
            <el-button
              style="background-color: #3d839c; color: #fff"
              @click="updateArea(scope.row)"
              >修改</el-button
            >
            <el-button
              v-if="scope.row.isDeleted == '正常'"
              type="danger"
              @click="endArea(scope.row.id)"
              >停用</el-button
            >
            <el-button v-else type="success" @click="startArea(scope.row.id)"
              >启用</el-button
            >
          </div>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination
        background
        layout="prev, pager, next"
        :total="tabelDataTotal"
        :page-size="query.pageSize"
        :current-page="query.pageNum"
        @update:current-page="currentPageChange"
      />
    </div>
    <!-- 添加、修改弹窗 -->
    <el-dialog v-model="dialogTableVisible" :title="title" width="400">
      <div class="dialog-win">
        <el-form
          ref="ruleFormRef"
          :model="table"
          label-width="auto"
          :rules="rules"
        >
          <el-form-item label="区域名称：" prop="name">
            <el-input v-model="table.name" style="width: 240px" />
          </el-form-item>
          <el-form-item label="区域地址：" prop="address">
            <el-cascader
              style="width: 240px; margin-bottom: 10px"
              placeholder="请选择地区"
              size="default"
              :options="regionData"
              @change="handleChange"
              v-model="selectedregionData"
            >
            </el-cascader>
            <el-input
              v-model="addressDetails"
              style="width: 240px"
              placeholder="详细地址"
            />
          </el-form-item>
          <el-form-item>
            <div class="from-but">
              <el-button type="warning" @click="submit(ruleFormRef)"
                >确定</el-button
              >
              <el-button type="info" @click="resetForm(ruleFormRef)"
                >取消</el-button
              >
            </div>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>
  <script setup>
import { CirclePlus } from "@element-plus/icons-vue";
import message from "@/util/alert.js";
import { ref, reactive, onMounted, watch, computed } from "vue";
import { regionData } from "element-china-area-data";
import { useConfigStore } from "@/stores";
const configStore = useConfigStore();
import {
  getAreaListApi,
  updateAreaApi,
  addAreaApi,
  startAreaApi,
  endAreaApi,
} from "@/api/areaApi.js";
// 查询参数
const query = reactive({
  queryName: "",
  pageNum: 1,
  pageSize: 10,
});
const selectedAddress = ref("");
const addressDetails = ref("");
const selectedregionData = ref([]);
// 选择省市县 地图数据
const handleChange = (value) => {
  selectedAddress.value = "";
  for (let i = 0; i < regionData.length; i++) {
    if (regionData[i].value == value[0]) {
      selectedAddress.value += regionData[i].label;
      for (let j = 0; j < regionData[i].children.length; j++) {
        let item = regionData[i].children[j];
        if (item.value == value[1]) {
          selectedAddress.value += item.label;
          for (let k = 0; k < item.children.length; k++) {
            let item2 = item.children[k];
            if (item2.value == value[2]) {
              return (selectedAddress.value += item2.label);
            }
          }
        }
      }
    }
  }
};
watch(selectedAddress, () => {
  table.value.address = selectedAddress.value + addressDetails.value;
});
watch(addressDetails, () => {
  table.value.address = selectedAddress.value + addressDetails.value;
});
const tabelDataTotal = ref(0);
const loading = ref(false);
const tabelData = ref([]);
// 表格头部样式
const headerStyle = () => {
  return {
    backgroundColor: "#a0cfff",
    color: "#000000",
    padding: "8px 0px",
  };
};
// 表格行内样式
const tableRowClassName = ({ row }) => {
  if (row.isDeleted != "正常") {
    return "danger-row";
  }
  return "";
};
// 当前页改变
const currentPageChange = (num) => {
  query.pageNum = num;
  getTabelData();
};
// 获取配置列表
const getTabelData = async () => {
  loading.value = true;
  let res = await getAreaListApi(query);
  configStore.areaList = res.data;
  tabelDataTotal.value = res.data.total;
  tabelData.value = res.data.rows;
  loading.value = false;
};
// 添加配置类型
const addArea = () => {
  table.value = {
    name: "",
    address: "",
  };
  addressDetails.value = "";
  selectedAddress.value = "";
  selectedregionData.value = [];
  title.value = "添加区域";
  dialogTableVisible.value = true;
};

// 修改配置类型信息
const updateArea = (row) => {
  table.value = JSON.parse(JSON.stringify(row));
  addressDetails.value = "";
  selectedAddress.value = "";
  selectedregionData.value = [];
  title.value = "修改区域信息";
  dialogTableVisible.value = true;
};
// 启用
const startArea = (id) => {
  message.confirm({
    title: "提示",
    msg: `是否启用此区域`,
    ok: async () => {
      await startAreaApi(id);
      message.success(`启用成功`);
      getTabelData();
    },
  });
};
// 停用
const endArea = (id) => {
  message.confirm({
    title: "提示",
    msg: `是否停用此区域`,
    ok: async () => {
      await endAreaApi(id);
      message.success(`停用成功`);
      getTabelData();
    },
  });
};
// 重置
const reset = () => {
  Object.assign(query, {
    queryName: "",
    pageNum: 1,
    pageSize: 10,
  });
  getTabelData();
};
// 弹窗
const table = ref({});
const dialogTableVisible = ref(false);
const title = ref("");
const ruleFormRef = ref(null);
// 添加、修改的规则
const rules = reactive({
  name: [
    { required: true, message: "请输入区域名称", trigger: "blur" },
    { min: 2, max: 20, message: "区域名称长度为2-20", trigger: "blur" },
  ],
  address: [
    { required: true, message: "请输入区域地址", trigger: "blur" },
    { min: 5, max: 50, message: "区域地址长度为5-50", trigger: "blur" },
  ],
});
// 提交表单
const submit = async (ruleForm) => {
  if (!ruleForm) return;
  await ruleForm.validate(async (valid, fields) => {
    if (valid) {
      if (title.value == "修改区域信息") {
        await updateAreaApi(table.value);
        getTabelData();
        dialogTableVisible.value = false;
        message.success("修改区域信息成功");
      } else if (title.value == "添加区域") {
        await addAreaApi(table.value);
        getTabelData();
        dialogTableVisible.value = false;
        message.success("添加区域成功");
      }
    }
  });
};
// 重置表单
const resetForm = (ruleForm) => {
  ruleForm.resetFields();
  dialogTableVisible.value = false;
  table.value = {};
};
onMounted(() => {
  getTabelData();
});
</script>
  <style lang="scss" scoped>
.main {
  width: 100%;
  height: 100%;
  background-color: #ffffff;
  padding: 10px 20px;
  .title {
    font-size: 20px;
    font-weight: 600;
    display: flex;
    justify-content: space-between;
  }
}
.search-bar {
  margin-top: 20px;
  display: flex;
  align-items: center;
  height: 30px;
  .search-btn {
    background-color: #79bbff;
    color: #ffffff;
  }
  .el-button {
    height: 28px;
  }
}
.label-input {
  display: flex;
  color: #aaaaaa;
  height: 30px;
  align-items: center;
  margin-right: 20px;
  font-weight: 550;
  .el-input {
    border: none;
    height: 30px;
  }
}
.cut-line {
  margin-top: 30px;
  height: 1px;
  background-color: #cdd0d6;
}

.pagination {
  display: flex;
  justify-content: center;

  .el-pagination {
    margin: auto 0;
    margin-top: 10px;
  }
}
:deep(.el-table) {
  margin-top: 20px;
  .el-table__cell {
    padding: 4px;
  }
  .cell {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}
</style>